// const { baseUrl } = require('../config/index');
import baseUrl from '../config/index'
console.log(baseUrl)
let defaultConfig = {
  isToastShow: true,
  code: '',
  title: '加载中',
  isLoadingShow: true
}
const showModal = (msg, isModalShow) => {
  if (!isModalShow) return;
  // wx.showModal({
  //     title: '提示',
  //     showCancel: false,
  //     content: msg,
  // })
  let config = {
    title: msg,
    icon: 'none',
    duration: 3000
  }
  // if (msg.length < 7) {
  // config = { ...config, ...{ image: '/static/images/tishi.png' } }
  // }
  wx.showToast(config)
}

function http(url, params, method = "POST", config = {
  header: {
    'content-type': 'application/json',
    'Authorization': wx.getStorageSync('token')
  }
}) {
  // config = { ...defaultConfig, ...config }
  // if (config.isLoadingShow) {
  //     wx.hideLoading();
  //     wx.showLoading({
  //         title: config.title,
  //         mask: true
  //     })
  // }
  return new Promise((resolve, reject) => {
    // console.log("这是一个："+method+"的请求")
    wx.request({
      method: method,
      header: config.header,
      url: `${baseUrl}${url}`,
      data: params,
      success: (res) => {
        // console.log('http-js==================res:',res)
        config.isLoadingShow && wx.hideLoading();
        switch (res.statusCode) {
          case 200:
            if (res.data.code == 0) {
              // console.log("200:",res.data.result)
              resolve(res.data.result)
            } else {
              // showModal(res.data.Msg, config.isToastShow);
              // !config.isToastShow && reject(res);
              reject(res);
            }
            break;
          case 404:
            showModal('资源未找到，请稍后重试', config.isToastShow)
            break;
          case 500:
            showModal('服务器错误，请稍后重试', config.isToastShow)
            break;
          default:
            showModal('服务器错误，请稍后重试', config.isToastShow)
            break;
        }
      },
      fail: function (res) {
        console.log('err:', res)
        config.isLoadingShow && wx.hideLoading();
        if (/(timeout|超时)/g.test(res.errMsg)) {
          showModal('网络超时，请稍后重试', true);
        } else {
          showModal('请求失败', true);
        }
      },
      complete(complete) {
        // console.log('complete:', complete)
      }
    })
  })
}

module.exports = http;